package com.itheima.websocket;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.itheima.entity.Message;
import com.itheima.entity.websocket.UserData;
import com.itheima.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Date;
import java.util.Map;

/**
 * @Description:接受消息和发送消息的处理逻辑类
 * @Date :2019-10-26 13:45
 * @Author : yuan_he_song
 */
@Component
public class MessageHandler extends TextWebSocketHandler {

    /** 存放用户session对象的map集合 */
    private static final Map<Integer, WebSocketSession> SESSION_MP = Maps.newHashMap();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private MessageMapper messageMapper;


    @Override /** 客户端和服务端建立连接后  */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        /** attribute 是 WebsocketInterceptor beforeHandshake()方法里的map */
        Map<String, Object> attributes = session.getAttributes();
        Integer uid = (Integer)attributes.get("uid");
        /** 将当前用户session存入SESSION_MAP中,后面会用session通信 */
        SESSION_MP.put(uid,session);
    }

    @Override /** 处理消息逻辑 */
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        Integer uid = (Integer) session.getAttributes().get("uid"); /** 发送者id */
        JsonNode jsonNode = objectMapper.readTree(textMessage.getPayload()); //取出消息内容
        int toId = jsonNode.get("toid").asInt(); // 发给谁的id
        String msg = jsonNode.get("msg").asText(); // 消息内容

        /** 封装消息数据 */
        Message message = Message.builder()
                .msg(msg).status(1).sendTime(new Date())
                .fromId(UserData.USER_MAP.get(uid).getUserId())
                .toId(UserData.USER_MAP.get(toId).getUserId()).build();
        /** 将消息保存到表 */
        messageMapper.insertSelective(message);

        /** 判断to用户是否在线 */
        WebSocketSession toSession = SESSION_MP.get(toId);
        if(toSession != null && toSession.isOpen()){
            String msgJson = objectMapper.writeValueAsString(message);
            toSession.sendMessage(new TextMessage(msgJson));
             /** 更新消息状态为已读 */
            message.setStatus(2);
            messageMapper.updateByPrimaryKeySelective(message);
        }
    }
}
